package com.abc.api;

import com.abc.config.SiliconflowProperties;
import com.abc.dto.request.RerankRequestDto;
import com.abc.dto.response.RerankResponseDto;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * Siliconflow API 客户端
 */
@Slf4j
@Component
public class SiliconflowApi {

    @Autowired
    private SiliconflowProperties siliconflowProperties;

    @Autowired
    private RestTemplate restTemplate;


    /**
     * 调用重排序接口
     * 
     * @param requestDto 重排序请求参数
     * @return 重排序结果
     */
    public RerankResponseDto rerank(RerankRequestDto requestDto) {
        log.info("调用 Siliconflow Rerank API，查询: {}, 文档数: {}", 
                requestDto.getQuery(), requestDto.getDocuments().size());
        
        try {
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("documents", requestDto.getDocuments());
            requestBody.put("model", requestDto.getModel());
            requestBody.put("query", requestDto.getQuery());
            requestBody.put("top_n", requestDto.getTopN());
            requestBody.put("return_documents", requestDto.getReturnDocuments());
            requestBody.put("max_chunks_per_doc", requestDto.getMaxChunksPerDoc());
            requestBody.put("overlap_tokens", requestDto.getOverlapTokens());

            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + siliconflowProperties.getApiKey());
            
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            
            String url = siliconflowProperties.getBaseUrl() + "/v1/rerank";
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            
            String responseJson = response.getBody();
            log.debug("Siliconflow API 响应: {}", responseJson);
            
            RerankResponseDto result = JSON.parseObject(responseJson, RerankResponseDto.class);
            
            if (result != null && result.getResults() != null) {
                log.info("Siliconflow Rerank API 调用成功，返回 {} 个结果", result.getResults().size());
            }
            
            return result;
        } catch (Exception error) {
            log.error("Siliconflow Rerank API 调用失败", error);
            throw new RuntimeException("Siliconflow Rerank API 调用失败: " + error.getMessage(), error);
        }
    }
}